import os 
import time, datetime
import random
from websocket import create_connection
global ws 
global url


#url="ws://10.12.2.220:19000"
#ws = create_connection(url)

def send_message(message):
    url = "ws://10.12.2.220:19000"
    # create connection to cluster
    ws = create_connection(url)
    try:
        ws.send(message)
        result =ws.recv()
        ws.close()
        print("send_message out===", result)
        return result
    except Exception as e:
        ws.close()
        print(e)
        return False
    finally:
        ws.close()

def check_work_status_by_work_id(work_id):
    action="check_work_status_by_work_id"
    message='{"action":"check_work_status_by_work_id","work_id":"%s"}'%work_id
    result=send_message(message)
    return result
def submit_job_socket(work_info):
    action="submit_job_socket"
    message='{"action":"%s","user_name":"%s","load_type":"%s","work_name":"%s","work_id":"%s","work_dir":"%s","wind_type":"%s","wind_path":"%s","DLC_sheet":"%s","pj":"%s","bladed_in":"%s","dll":"%s","ctr_xml":"%s","blade_xml":"%s","short_2":"%s","short_3":"%s"}'%(action,work_info['user_name'],work_info['load_type'],work_info['work_name'],work_info['work_id'],work_info['work_dir'],work_info['wind_type'],work_info['wind_path'],work_info['DLC_sheet'],work_info['pj'],work_info['bladed_in'],work_info['dll'],work_info['ctr_xml'],work_info['blade_xml'],work_info['short_2'],work_info['short_3'])
    if debug:
        print(message)
    send_message(message)
def create_work_id():
    return str(int(time.time()))+str(random.randint(0,1000))

#submit_job_socket(work_info)
#work_id=create_work_id()
#print(work_id)


#action="check_work_status_by_work_id"
#message='{"action":"check_work_status_by_work_id","work_id":"%s"}'%work_id
"""
提交计算任务测试模型
推建 使用 create_work_id() 函数获取work_id
所有提交计算任务都可以在 http://10.12.2.220:9000 这个平台上访问
"""

#action="check_work_status_by_work_id"
#message='{"action":"check_work_status_by_work_id","work_id":"%s"}'%work_id
#print(message)
#ws.send(message)
#result =ws.recv()
#check work status
#result=check_work_status_by_work_id(work_id)
#print(result)

if __name__=='__main__':
    import ControllerXmlFunctions as ctl_xml
    import random
    from websocket import create_connection
    global ws
    global url
    import shutil
    # start = time.clock()
    #work_info = {}
    #work_info = dict(work_info)
    # file the string
    debug = True
    data_list = [[0.7, 1.0], [-0.01745, 0.0949]]

    work_info = {"action": "newtask_job_submit"
        , "user_name": "zhangxuedong30595"
        , "load_type": "A"
        , "work_name": "michael_test_01"
        , "work_id": "20191113023551547"
        , "work_dir": "\\\\10.1.253.49\\dingzhihua\\zhangxuedong30595\\demo_01\\"
        , "wind_type": "yes"
        , "wind_path": ""
        , "DLC_sheet": "Goldwind_LoadCase_define_IEC4th_adaptability_analysis_18ms_strom_GW150-2.8_V2_demo_01.xls"
        , "pj": "GW150P2800TG100_1527BGW73.2_V2.$PJ"
        , "bladed_in": "dtbladed.in"
        , "dll": "GW150P2800TG100NXXX252TBGW73.2V475_CFII_V5.01.03.01.dll"
        , "ctr_xml": "GW150P2800TG100NXXX252TBGW73.2V475_CFII_V5.01.03.01.xml"
        , "blade_xml":""
        , "short_2": ""
        , "short_3": ""}
    #submit_job_socket(work_info)
    #initial work_inof data

    debug = True
    sumit_sign = False
    P_step = 200000
    P_start = 95000
    P_end = 2550000 + P_step
    T_step = 0.008725
    T_start = -0.01745
    T_end = 0.1047 + T_step
    T_iter = 0.0
    channel_name_P = "P_YawErrorDeratingPower"
    table_name_T = "T_FinePitchScheduleYaw"
    data_list = [[0.7, 1.0], [-0.01745, 0.0949]]
    #make some chg if needed
    #file_name = "GW150P2800TG100NXXX252TBGW73.2V475_CFII_V5.01.03.01.xml"
    output_dir = "\\\\10.1.253.49\\dingzhihua\\zhangxuedong30595\\\test\\"
    dlc_sheets = "Goldwind_LoadCase_define_IEC4th_adaptability_analysis_18ms_strom_GW150-2.8_V2_demo_01.xls"
    pj_name = "GW150P2800TG100_1527BGW73.2_V2.$PJ"
    IN_file = "dtbladed.in"
    dll_ctl = "GW150P2800TG100NXXX252TBGW73.2V475_CFII_V5.01.03.01.dll"
    # random get a work id
    #work_info['work_name'] = "michael_test_01"
    #work_info['DLC_sheet'] = dlc_sheets
    #work_info['pj'] = pj_name
    #work_info['bladed_in'] = IN_file
   # work_info['dll'] = dll_ctl
    #work_info['ctr_xml'] = file_name
    #work_info['work_id']= create_work_id()
    #submit_job_socket(work_info)
    #if debug:
    #   work_info['work_id'] = create_work_id()
    #   submit_job_socket(work_info)
    file_n1 = work_info["ctr_xml"]
    output_base_dir = "\\\\10.1.253.49\\dingzhihua\\zhangxuedong30595\\demo_01\\"
    file_name = os.path.join(output_base_dir, file_n1 )
    if debug:
        print("file_name",file_name)

    # begin iteration
    for P_yaw_error in range(P_start, P_end, P_step):
        result_path_base = os.path.join(output_base_dir, str(P_yaw_error))
        if os.path.exists(result_path_base):
            shutil.rmtree(result_path)
        os.makedirs(result_path_base)
        if debug:
            print("\n======yaw_error input=====", P_yaw_error)
        # replace value to xml file
        val = P_yaw_error
        channel_name = channel_name_P
        try:
            ctl_xml.controller_para_modify(channel_name, val, file_name)
        except Exception as err:
            print("ERROR Channel value replace is", err)
      
        for T_FinePitch in range(1, 15, 1, ):

            if T_FinePitch == 1:
                T_iter = T_start
            if T_FinePitch > 1:
                T_iter = T_iter + T_step
                if debug:
                    print("======T_FinePitch input ========", T_iter)
            # chg xml file on table
            table_name = table_name_T

            # chg list value replace with T_iter
            data_list[1][1] = T_iter
            try:
                index, info = ctl_xml.controller_table_modify(table_name, data_list, file_name)
            except Exception as err:
                print("ERROR table value replace is : ", err)
            if debug:
                flag, data_rd = ctl_xml.controller_data_read(file_name)
                print("\nreplace action returned value \n ", index, info)
                print("\n-------check replacement---------\n")
                print(data_rd['Table']['T_FinePitchScheduleYaw']['Row']['2']['_1'])

            #check if did before,so delete dirs and make a new one to iteration
            result_path = os.path.join(result_path_base, 'Result_D{:0>2d}'.format(T_FinePitch))
            print(result_path)
            if os.path.exists(result_path):
                shutil.rmtree(result_path)
            os.makedirs(result_path)
            # copy files to the new dir
            file1 = os.path.join(output_base_dir, work_info["DLC_sheet"])
            file2 = os.path.join(result_path, work_info["DLC_sheet"])
            shutil.copyfile(file1, file2)
            file1 = os.path.join(output_base_dir, work_info["pj"])
            file2 = os.path.join(result_path, work_info["pj"])
            shutil.copyfile(file1, file2)
            file1 = os.path.join(output_base_dir, work_info["bladed_in"])
            file2 = os.path.join(result_path, work_info["bladed_in"])
            shutil.copyfile(file1, file2)
            file1 = os.path.join(output_base_dir, work_info["dll"])
            file2 = os.path.join(result_path, work_info["dll"])
            shutil.copyfile(file1, file2)
            file1 = os.path.join(output_base_dir, work_info["DLC_sheet"])
            file2 = os.path.join(result_path, work_info["DLC_sheet"])
            shutil.copyfile(file1, file2)
            file1 = os.path.join(output_base_dir, work_info["ctr_xml"])
            file2 = os.path.join(result_path, work_info["ctr_xml"])
            shutil.copyfile(file1, file2)
            # replace a new dir to work_dir
            print(work_info["work_dir"])
            work_info["work_dir"] = result_path + "\\"
            # sumit jobs
            #time.sleep(5)
            #create a new id and sumit jobs

            if sumit_sign:
                work_info['work_id'] = create_work_id()
                submit_job_socket(work_info)
                # check work status
                result = check_work_status_by_work_id(work_id_new)
                print (" status is -------", result)
            if debug:
                print(work_info["work_dir"])

    print(" iter finished ")


